<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of SalesforceClient
 *
 * @author HP
 */
//require_once(dirname(dirname(__FILE__))."/calendarSyncCommon.php");
class SalesforceClient extends Salesforce {
    public static function delete(array $Ids) {
        $conn = Salesforce::connect();
        $result = null;
        try {
            $result = $conn->delete($Ids);
        } catch (Exception $e) {
            $result = $e;
        }

        return $result;
    }
    
    public static function upsert($data, $idField = "Id") {
        CalendarSyncUtil::debug('upser data', $data);
        $conn = Salesforce::connect();
        $records = (is_array($data) ? $data : array($data));
        foreach ($records as $rec) {
            if(!isset($rec->Id)){
                $rec->fields = CalendarSyncUtil::cleanFields($rec->type, $rec->fields, FALSE);
            }
        }
        $result = null;
        try {
            $result = $conn->upsert($idField, $records);
        } catch (Exception $e) {
            $result = $e;
        }

        return $result;
    }
    
    public static function queryRecords($query, $queryType){
        $result = null;
        try {
            $conn = Salesforce::connect();
            $options = new QueryOptions(1000);
            $conn->setQueryOptions($options);
            $queryResult = Salesforce::sfQueryProxy($conn, $queryType, $query);

            $queryLocator = $queryResult->queryLocator;
            $size =  $queryResult->size;
            $records = $queryResult->records;
            $done = $queryResult->done;

            while(!$done){
                $temp_result = Salesforce::sfQueryProxy($conn, $queryType, $queryLocator);
                $done = $temp_result->done;
                $queryLocator = $temp_result->queryLocator;
                $size += $temp_result->size;
                $records = array_merge($records, $temp_result->records);            
            }
            $queryResult->done = $done;
            $queryResult->queryLocator = $queryLocator;
            $queryResult->records = $records;
            $result = array("isSuccess"=>true, "queryResult"=>$queryResult);
        }
        catch(Exception $e) {
            $result = array("isSuccess" => false, "query" => $query, "exception" => $e, "error"=>$e->getMessage());
        }
        return $result;
    }
}
?>
